package com.mall.shopping.services;

import com.mall.shopping.ICartService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.converter.CartItemConverter;
import com.mall.shopping.dal.entitys.Item;
import com.mall.shopping.dal.persistence.ItemMapper;
import com.mall.shopping.dto.*;
import org.apache.dubbo.config.annotation.Service;
import org.redisson.api.RMap;
import org.redisson.api.RScoredSortedSet;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

@Service
public class CartServiceImpl implements ICartService {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    ItemMapper itemMapper;


    /**
     * 获取购物车列表
     *
     * @param request
     * @return
     */
    @Override
    public CartListByIdResponse getCartListById(CartListByIdRequest request) {
        CartListByIdResponse response = new CartListByIdResponse();
        try {
            request.requestCheck();
            //获取购物车
            RMap<Long, CartProductDto> map = redissonClient.getMap("cart:userId:" + request.getUserId());

            //获取成功
            if (map != null) {
                //购物车商品
                List<CartProductDto> list = new ArrayList<>();

                //根据列表进行排序
                if (map.size() > 0) {
                    RScoredSortedSet<Long> scoredSortedSet = redissonClient.getScoredSortedSet("cartTime:userId:" + request.getUserId());
                    List<Long> cartTime = new ArrayList<>(scoredSortedSet.readAll());
                    for (int i = 0; i < cartTime.size(); i++) {
                        CartProductDto cartProductDto = map.get(cartTime.get(cartTime.size() - i - 1));
                        if (cartProductDto != null) {
                            list.add(cartProductDto);
                        }
                    }
                }

                //返回购物车列表
                response.setCartProductDtos(list);
                response.setCode(ShoppingRetCode.SUCCESS.getCode());
                response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            response.setMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
        }
        //获取失败

        return response;
    }

    /**
     * 添加商品到购物车
     *
     * @param request
     * @return
     */
    @Override
    public AddCartResponse addToCart(AddCartRequest request) {
        AddCartResponse response = null;

        try {
            //获取map
            RMap<Long, CartProductDto> map = redissonClient.getMap("cart:userId:" + request.getUserId());
            //查看是否已经添加了商品
            CartProductDto cartProductDto = map.get(request.getItemId());
            response = new AddCartResponse();
            if (cartProductDto != null) {
                //判断商品数量是否达用户到上限
                //未达到上限则添加，达到上限则失败
                if (cartProductDto.getLimitNum() >= (cartProductDto.getProductNum() + request.getNum())) {
                    //说明商品数量未达到上限，可以继续添加
                    cartProductDto.setProductNum(cartProductDto.getProductNum() + request.getNum());

                    //放入redis
                    map.put(cartProductDto.getProductId(), cartProductDto);
                    response.setCode(ShoppingRetCode.SUCCESS.getCode());
                    response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
                    return response;
                }

                //添加失败
                response.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
                response.setMsg("添加失败,个人最多拥有该商品" + cartProductDto.getLimitNum() + "件！");
                return response;
            }


            //如果没有则去数据库查询
            Item item = itemMapper.selectByPrimaryKey(request.getItemId());
            //判断数量是否达到上限
            if (item != null && item.getLimitNum() >= request.getNum()) {
                //转换为dto
                CartProductDto cartProductDtoToAdd = CartItemConverter.item2Dto(item);
                //赋值
                cartProductDtoToAdd.setProductNum(Long.valueOf(request.getNum()));
                cartProductDtoToAdd.setChecked("true");
                //添加到redis中
                map.put(cartProductDtoToAdd.getProductId(), cartProductDtoToAdd);
                //添加时间进行排序
                RScoredSortedSet<Long> scoredSortedSet = redissonClient.getScoredSortedSet("cartTime:userId:" + request.getUserId());
                scoredSortedSet.add(((double) System.currentTimeMillis()), cartProductDtoToAdd.getProductId());

                //返回
                response.setCode(ShoppingRetCode.SUCCESS.getCode());
                response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
                return response;
            }
            //添加失败
            response.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            response.setMsg("添加失败,个人最多拥有该商品" + item.getLimitNum() + "件！");
        } catch (Exception e) {
            e.printStackTrace();
            response.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            response.setMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
        }
        return response;
    }


    /**
     * 更新购物车中商品的数量
     *
     * @param request
     * @return
     */
    @Override
    public UpdateCartNumResponse updateCartNum(UpdateCartNumRequest request) {
        UpdateCartNumResponse response = new UpdateCartNumResponse();
        try {
            request.requestCheck();
            if (request.getProductNum() == 0) {
                DeleteCartItemRequest deleteCartItemRequest = new DeleteCartItemRequest();
                deleteCartItemRequest.setUserId(Long.parseLong(request.getUserId()));
                deleteCartItemRequest.setItemId(request.getProductId());
                deleteCartItem(deleteCartItemRequest);
                response.setCode(ShoppingRetCode.SUCCESS.getCode());
                response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
            } else {
                RMap<Long, CartProductDto> map = redissonClient.getMap("cart:userId:" + request.getUserId());
                CartProductDto s = map.get(request.getProductId());
                s.setProductNum(Long.valueOf(request.getProductNum()));
                s.setChecked(request.getChecked());
                map.put(request.getProductId(), s);
                response.setCode(ShoppingRetCode.SUCCESS.getCode());
                response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            response.setMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
        }

        return response;
    }


    /**
     * 删除购物车中的商品
     *
     * @param request
     * @return
     */
    @Override
    public DeleteCartItemResponse deleteCartItem(DeleteCartItemRequest request) {
        DeleteCartItemResponse response = new DeleteCartItemResponse();
        try {
            request.requestCheck();
            RMap<Long, CartProductDto> map = redissonClient.getMap("cart:userId:" + request.getUserId());
            map.remove(request.getItemId());
            RScoredSortedSet<Long> scoredSortedSet = redissonClient.getScoredSortedSet("cartTime:userId:" + request.getUserId());
            scoredSortedSet.remove(request.getItemId());
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            response.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            response.setMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
        }
//需要修改

        return response;
    }

    /**
     * 删除选中的商品
     *
     * @param request
     * @return
     */
    @Override
    public DeleteCheckedItemResposne deleteCheckedItem(DeleteCheckedItemRequest request) {
        DeleteCheckedItemResposne response = new DeleteCheckedItemResposne();
        try {
            request.requestCheck();
            RMap<Long, CartProductDto> map = redissonClient.getMap("cart:userId:" + request.getUserId());
            RScoredSortedSet<Long> scoredSortedSet = redissonClient.getScoredSortedSet("cartTime:userId:" + request.getUserId());

            List<CartProductDto> values = new ArrayList(map.values());
            for (CartProductDto value : values) {
                if ("true".equals(value.getChecked())) {
                    map.remove(value.getProductId());
                    scoredSortedSet.remove(value.getProductId());
                }
            }
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            response.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            response.setMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
        }
//需要修改
        return response;
    }

    /**
     * 选择购物车中的所有商品
     *
     * @param request
     * @return
     */
    @Override
    public CheckAllItemResponse checkAllCartItem(CheckAllItemRequest request) {
        CheckAllItemResponse response = new CheckAllItemResponse();
        try {
            request.requestCheck();
            RMap<Long, CartProductDto> map = redissonClient.getMap("cart:userId:" + request.getUserId());
            List<CartProductDto> values = new ArrayList(map.values());
            for (CartProductDto value : values) {
                if (!value.getChecked().equals(request.getChecked())) {
                    value.setChecked(request.getChecked());
                    map.put(value.getProductId(), value);
                }
            }
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            response.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            response.setMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
        }
//需要修改
        return response;
    }

    /**
     * 清空指定用户的购物车缓存(用户下完订单之后清理）
     *
     * @param request
     * @return
     */
    @Override
    public ClearCartItemResponse clearCartItemByUserID(ClearCartItemRequest request) {
        ClearCartItemResponse response = new ClearCartItemResponse();
        try {
            request.requestCheck();
            RMap<Long, CartProductDto> map = redissonClient.getMap("cart:userId:" + request.getUserId());
            RScoredSortedSet<Long> scoredSortedSet = redissonClient.getScoredSortedSet("cartTime:userId:" + request.getUserId());

            List<Long> productIds = request.getProductIds();
            for (Long productId : productIds) {
                if (map.containsKey(productId)) {
                    scoredSortedSet.remove(productId);
                    map.remove(productId);
                }
            }

//需要修改
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            response.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            response.setMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
        }

        return response;
    }
}
